#通过形状匹配来进行识别

import cv2
import numpy

threshold_ret = 0.0

image_shitou_bgr = cv2.imread("images/shitou.png")
if image_shitou_bgr is None:
    print("imread error\n")
    exit(1)

image_shitou_gray = cv2.cvtColor(image_shitou_bgr, cv2.COLOR_BGR2GRAY)
# cv2.imshow("image_shitou_gray", image_shitou_gray)
threshold_ret, image_shitou_binary = cv2.threshold(image_shitou_gray, 128.0, 255.0, cv2.THRESH_BINARY)
contours_shitou, hierarchy = cv2.findContours(image_shitou_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

image_jiandao_bgr = cv2.imread("images/jiandao.png")
if image_jiandao_bgr is None:
    print("imread error\n")
    exit(1)
    
image_jiandao_gray = cv2.cvtColor(image_jiandao_bgr, cv2.COLOR_BGR2GRAY)
# cv2.imshow("image_jiandao_gray", image_jiandao_gray)
threshold_ret, image_jiandao_binary = cv2.threshold(image_jiandao_gray, 128.0, 255.0, cv2.THRESH_BINARY)
contours_jiandao, hierarchy = cv2.findContours(image_jiandao_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    
image_bu_bgr = cv2.imread("images/bu.png")
if image_bu_bgr is None:
    print("imread error\n")
    exit(1)
    
image_bu_gray = cv2.cvtColor(image_bu_bgr, cv2.COLOR_BGR2GRAY)
# cv2.imshow("image_bu_bgr", image_bu_bgr)
threshold_ret, image_bu_binary = cv2.threshold(image_bu_gray, 128.0, 255.0, cv2.THRESH_BINARY)
contours_bu, hierarchy = cv2.findContours(image_bu_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

video_capture = cv2.VideoCapture(0)
ret = video_capture.open(0)
if not ret:
    print("open error\n")
    exit(1)
    
while True:
    ret, capture = video_capture.read()
    if not ret:
        cv2.waitKey(40)
        continue
        
    if capture is None:
        cv2.waitKey(40)
        continue
        
    cv2.imshow("capture", capture)
    
    capture_gray = cv2.cvtColor(capture, cv2.COLOR_BGR2GRAY)
    cv2.imshow("capture_gray", capture_gray)
        
    threshold_ret, capture_binary = cv2.threshold(capture_gray, 128.0, 255.0, cv2.THRESH_BINARY)
    cv2.imshow("capture_binary", capture_binary)
        
    contours_capture, hierarchy = cv2.findContours(capture_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        
    score = cv2.matchShapes(contours_capture[0], contours_shitou[0], cv2.CONTOURS_MATCH_I1, 0.0)
    if score < 0.1:
        print("shi tou")
        print(score)
        cv2.waitKey(40)
        continue
        
    score = cv2.matchShapes(contours_capture[0], contours_jiandao[0], cv2.CONTOURS_MATCH_I1, 0.0)
    if score < 0.1:
        print("jian dao")
        print(score)
        cv2.waitKey(40)
        continue
        
    score = cv2.matchShapes(contours_capture[0], contours_bu[0], cv2.CONTOURS_MATCH_I1, 0.0)
    if score < 0.1:
        print("bu")
        print(score)
        cv2.waitKey(40)
        continue
    
    cv2.waitKey(40)
